package com.czk.exception;

import com.czk.jdbctemplate.dao.DeptDap;
import com.czk.jdbctemplate.entity.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/9/10 14:53
 */
@Controller
public class ExceptionController {
    @Autowired
    private DeptDap deptDap;

    @Transactional(rollbackFor = MyException.class)

    public void test(int age) {
        Department department = new Department();
        department.setDepartmentName("czk");
        deptDap.add(department);
        if (age < 10) {
            throw new MyException("成绩小于十岁");
        }
        // 此时会回滚
        /**
         * org.springframework.transaction.interceptor.RollbackRuleAttribute#getDepth(java.lang.Throwable)
         *     private int getDepth(Class<?> exceptionClass, int depth) {
         *         if (exceptionClass.getName().contains(this.exceptionName)) {
         *             return depth;
         *         } else {
         *             return exceptionClass == Throwable.class ? -1 : this.getDepth(exceptionClass.getSuperclass(), depth + 1);
         *         }
         *     }
         *
         *     这里面用的contain
         *     所以：com.czk.exception.MyException2 是contain com.czk.exception.MyException的，此时抛出myException2也会回滚
         *     这也算spring的一个issue
         */
        if (age > 20) {
            throw new MyException2("成绩大于20");
        }
    }
}
